<?php 
include("../amazon_api_class.php");
include("../application/dataAccess.php");
include("../view/citation_list_functions.php");
include_once "api/wcapi_opensearch.php";
session_start();

$da = new dataAccess();
$UserID = trim($_SESSION['user_id']);
if($UserID == "")
{
	$UserID = session_id();		
}

$tr = isset($_GET['tr']) ? intval($_GET['tr']) : 0;
if($tr != 0) {
	$sql = "SELECT * FROM tbl_references WHERE User='".$UserID."' AND ID='".$tr."'";
	$res = mysql_query($sql);
	$result = mysql_fetch_assoc($res);
	$title_reference_id = $result['ID'];
	$title_reference = $result['Title_Reference'];	
} else {
	$sql = "SELECT * FROM tbl_references WHERE User='".$UserID."' ORDER BY CreatedDate DESC LIMIT 1";
	$res = mysql_query($sql);
	$result = mysql_fetch_assoc($res);
	$num = mysql_num_rows($res);
	if($num == 1) {
		$title_reference_id = $result['ID'];		
	} else {
		$d = date("Y-m-d H:i:s");
		$sql2 = "INSERT INTO tbl_references SET Title_Reference='Untitled references', User='".$UserID."', CreatedDate='".$d."', UpdatedDate='".$d."'";
		$res2 = mysql_query($sql2);		
		$title_reference_id = mysql_insert_id();
	}	
}

function getDoupleQuoteText($text)
{
	return str_replace("'", "''", $text);
}

function quoteAndDoubleQuoteJS($text)
{
	return str_replace('"', '&#34', str_replace("'", "\\'", $text));
}

function insertBookReferences($title, $publisher, $city, $year, $edition, $firstname, $lastname, $auth, $username, $title_rf, $isbn)
{
	if(isset($_SESSION['ReferenceCode']))
	{
		$codes = $_SESSION['ReferenceCode'];
	}
	else
	{
		$_SESSION['ReferenceCode'] = date("Ymdhis");
		$codes = $_SESSION['ReferenceCode'];
	}
	
	$sql = "SELECT * FROM composedocument WHERE isbn ='" . getDoupleQuoteText($isbn) . "' AND username='" . getDoupleQuoteText($username) . "' AND types='book' AND title_reference='$title_rf'";
	$resultQuery = mysql_query($sql);
	$countDB = mysql_num_rows($resultQuery);
	if ($countDB == 0)
	{
		$str  = "insert into composedocument set booktitle='". getDoupleQuoteText($title) . "',publisher='" . getDoupleQuoteText($publisher) . "',";
		$str .= "pcity='" . getDoupleQuoteText($city)."',pyear='". getDoupleQuoteText($year) . "',edition='".getDoupleQuoteText($edition) . "',";
		$str .= "firstname='" . getDoupleQuoteText($firstname) . "',lastname='" . getDoupleQuoteText($lastname) . "',";
		$str .= "author='". getDoupleQuoteText($auth) . "', isbn ='" . getDoupleQuoteText($isbn) . "',username='" . getDoupleQuoteText($username) . "',types='book',reference='$codes', title_reference='$title_rf'";			
		$data = mysql_query($str);	
		if ($data)
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
	else
	{
		return -1;
	}
}

function getPublisherCityByISBN($isbn)
{
	$key = "AMDHCmf0v6LFGqQ0veCwv5sISTqNoo3cre4zAMMZ6h02e4sW9qmPPVKNSXk0DeTAP05vsjXcoknZUt86";
	$query = $isbn;;
	$format = "rss";
	$start = 1;
	$count  = 1;
	$cformat = "apa";
	
	$publisher_city = "";
	$data = worldcat_opensearch($key,$query,$format,$start,$count,$cformat);
	if (count($data) > 0)
	{
		$item = $data[0];						
		$text = $item['content'];		
		if (strlen($text) > 5)
		{
			$pos = strpos($text, ": ");
			if ($pos > 0)
			{
				$temp_text = substr($text, 0, $len - 5);
				$index1 = lastIndexOf($temp_text, ": ");
				$index2 = lastIndexOf($temp_text, ". ");
				if ($index1 > 0 && $index2 > 0)
				{
					$publisher_city = substr($text, $index2, $index1 - $index2 - 2);					
				}				
			}
		}
	}	
	return $publisher_city;
}

function lastIndexOf($text, $key)
{
	$temp = strrev($text);
	$tempKey = strrev($key);
	$pos = strpos($temp, $tempKey);
	if ($pos > 0)
	{
		return strlen($temp) - $pos;
	}
	else
	{
		return -1;
	}
}

function getEditionFromRawData($item)
{
	$edition = "";	
	if (isset($item->ItemAttributes->Edition))
	{
		for($eIndex = 1; $eIndex < 20; $eIndex++)
		{
			//convert to text
			$temp_edition = $eIndex . "";
			$pos = strpos($item->ItemAttributes->Edition, $temp_edition);			
			if ($pos >= 0)
			{
				if ($eIndex == 1)
				{
					$edition = "1st ed.";
				}
				else if ($eIndex == 2)
				{
					$edition = "2nd ed.";
				}
				else if ($eIndex == 3)
				{
					$edition = "3rd ed.";
				}
				else
				{
					$edition = $pos . "th ed.";
				}									
				
				break;
			}
		}
	}
	return $edition;
}

$title_rf = $title_reference_id;

if(isset($_GET['val']) && $_GET['val']!="")
{
    $obj = new AmazonProductAPI();
    
	$titles = split(";", $_GET['val']);
	$countTitle = count($titles);
	if ($countTitle > 1)
	{
		try
		{
			$count_found_data = 0;
			$separated_item = "@#kk$%";
			$separated_items = "@#009900$%";
			$data_hidden = "";
			$arrLoaded = array();
			$totalSuccess = 0;
			for ($i = 0; $i < $countTitle; $i++)
			{			
				$title = trim($titles[$i]);
				$title = strtolower($title);
				if ($title != "" && !in_array($title, $arrLoaded))
				{
					$arrLoaded[] = $title;
					try
					{
						$data = $obj->searchProducts($title,
										   AmazonProductAPI::DVD,
										   "TITLE",1);						
					}
					catch(Exception $errTitle)
					{
						continue;
					}
					
					foreach ($data->Items->Item as $item)
					{
						//var_export($item->ItemAttributes);						
						//echo "<br/>";
						//echo "<br/>";
						//continue;
						
						$all_name = trim(preg_replace("/\([^\)]+\)/", "", $item->ItemAttributes->Author[0]));						
						$exp = explode(",",$all_name);			
						$count = count($exp);
						$result = "";			
						$year_arr = split("-", $item->ItemAttributes->PublicationDate);
						$year = $year_arr[0];
						
						//find edition
						$edition = getEditionFromRawData($item);
						
						$publisher_city = "";						
						$publisher_city = $da->search_city_by_publisher($item->ItemAttributes->Publisher);						
						if ($publisher_city == "")
						{
							$publisher_city = getPublisherCityByISBN($item->ItemAttributes->ISBN);
						}
						
						$work = array(
							edition => $edition,
							booktitle => $item->ItemAttributes->Title,
							pcity => $publisher_city,
							publisher => $item->ItemAttributes->Publisher,
							pyear => $year,
							author => $all_name,
							isbn => $item->ItemAttributes->ISBN
						);
															
						$lastName = "";
						$firstName = "";
												
						if ($count == 1)
						{				
							$temp = explode(' ', $exp[0]);
							$firstName = $temp[0];
							$lastName = getLastName($exp[0]);
							$result = $lastName . ", " . getInitialFirstName($exp[0]) . ".";
						}
						else
						{
							for($i = 0; $i < $count; $i++)
							{
								$lastName = getLastName($exp[$i]);													
								if( $i == $count - 1)
								{
									if ($count < 7)
									{
										$result .= "&" . $lastName . ", " . getInitialFirstName($exp[$i]);
									}
									else
									{
										$result .= "..." . $lastName . ", " . getInitialFirstName($exp[$i]);
									}									
								}
								else
								{
									$result .= $lastName . ", " . getInitialFirstName($exp[$i]) . "., ";									
								}						
							}
						}
						
						$totalSuccess += insertBookReferences($work['booktitle'], $work['publisher'], $work['pcity'], 
						$work['pyear'], $edition, $firstName, $lastName, "", $UserID, $title_rf, $work['isbn']);
						$count_found_data++;							
						break;
					}
				}	
			}

			if ($count_found_data > 0)
			{
				if (($totalSuccess + $count_found_data)> 0)
				{
					echo "Your references have been generated successfully.";
				}
				else
				{
					echo "<script type='text/javascript'>alert('Your reference has been generated');</script>";
				}
			}
			else
			{
				echo "Book was not found";
			}
			
		}
		catch(Exception $e)
		{
			echo $e->getMessage();
		}
	}
	else
	{
		try
		{
			$result = $obj->searchProducts($_GET['val'],
										   AmazonProductAPI::DVD,
										   "TITLE",$_GET['pages']);
			
			$totalpage = $result->Items->TotalPages;
			$TotalResults = $result->Items->TotalResults;
			$saw = (($_GET['pages']*10)<$TotalResults)? ($_GET['pages']*10) : $TotalResults;
			echo "<div class='font12' style='padding-top:5px;' align='left'> Total Search Records : <b>".$saw."</b> on <b>".$TotalResults."</b></div><br>";
			$isFirst = true;
			foreach ($result->Items->Item as $item)
			{
				?>
				<div class="product" style="width:370px; padding:5px 5px 5px 5px;">
				<table width="100%" style="width:370px; border:1px solid #E4E4E4; padding:3px 3px 3px 3px;" border="0" align="center" cellpadding="0" cellspacing="0">
				  <tr>
					<td width="22%" align="center" valign="middle">
					<a href="<?php echo $item->DetailPageURL;?>" target="_blank">
					<img src="<?php echo $item->SmallImage->URL;?>" border="0" /></a>
					</td>
					<td width="69%" align="left" valign="middle" class="font12">
					<?php  
						$edition = getEditionFromRawData($item);
						
						if($item->ItemAttributes->Title!=""){echo htmlentities($item->ItemAttributes->Title) . "<br>";}
						if($item->ItemAttributes->Author!=""){echo "By: " . htmlentities($item->ItemAttributes->Author) . "<br>";}
						if($item->ItemAttributes->Publisher!=""){echo htmlentities($item->ItemAttributes->Publisher) . "<br>";}
						if($item->ItemAttributes->ISBN!=""){echo "ISBN: " . htmlentities($item->ItemAttributes->ISBN) . "<br>";}
						if($edition != ""){ echo "Edition: " . htmlentities($edition) . "<br/>";}
						if($item->ItemAttributes->PublicationDate!=""){echo htmlentities($item->ItemAttributes->PublicationDate) . "<br>";}
						
						$publisher_city = $publisher_city = $da->search_city_by_publisher($item->ItemAttributes->Publisher);
						
						if ($publisher_city == "" && $isFirst)
						{
							$isFirst = false;
							$publisher_city = getPublisherCityByISBN($item->ItemAttributes->ISBN);							
						}
						
						//find edition
						
						//var_export($item->ItemAttributes);
						?></td>
					<td width="9%" align="center" valign="middle">
					<a href="javascript:void(0);" onclick="showbooksinfo('<?php echo quoteAndDoubleQuoteJS($item->ItemAttributes->Title);?>','<?php echo quoteAndDoubleQuoteJS($item->ItemAttributes->Author);?>','<?php echo quoteAndDoubleQuoteJS($item->ItemAttributes->Publisher);?>','<?php echo quoteAndDoubleQuoteJS($item->ItemAttributes->PublicationDate);?>','<?php echo quoteAndDoubleQuoteJS($publisher_city); ?>','<?php echo quoteAndDoubleQuoteJS($edition); ?>','<?php echo quoteAndDoubleQuoteJS($item->ItemAttributes->ISBN); ?>');">
					<img src="./images/select.png" border="0" /></a>
					</td>
				  </tr>
				</table>
				</div>
				<?php
			}
			if($totalpage>$_GET['pages'])
			{
				$next = ($_GET['pages']+1);
				?>
				<a href="javascript:void(0)" id="more<?php echo $next;?>" onclick="getbooks('<?php echo $next;?>')" class="font12" style="padding:5px 5px 1px 5px;"><img src="../images/more.png" border="0" /></a>
				<?php
			}	
			for($i=1;$i<=$totalpage;$i++){
			?>    
			<span id="booksmore<?php echo $i;?>"></span>
			<?php }?>
			<script>
			<?php
			$moreimg = ($_GET['pages']+1);
			if($moreimg>=3)
			{
				for($j=($moreimg-1);$j>=1;$j--){?>
				$("#more<?php echo $j;?>").hide();
			<?php }
			}
		}
		catch(Exception $e)
		{
			//echo $e->getMessage();			
			echo "Book was not found";
		}

		
	}
}
	?>
	

</script>